#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define ERR_EXIT(m) do { perror(m); exit(EXIT_FAILURE); } while(0)

void Rwork(int _rfd)
{
    while(1)
    {
        char buf[1024];
        ssize_t rsz = read(_rfd,buf,sizeof(buf)-1);
        buf[rsz] = 0;
        if(rsz < 0)
            ERR_EXIT("read");
        else if(rsz == 0)
        {
            printf("输入为0,exit\n");
            break;
        }
        else
        {
            printf("child: %s\n",buf);
        }
    }
}

void Wwork(int _wfd)//写
{
    int n = 3;
    std::string buf;
    while(1)
    {   
        n--;
            //char buf[512] = "hello world";
        printf("parent say: ");
        std::getline(std::cin,buf);
        ssize_t sz = write(_wfd,buf.c_str(),strlen(buf.c_str()));
        sleep(1);
        if(sz < 0)
            ERR_EXIT("write");
        else if(sz != strlen(buf.c_str()))
            ERR_EXIT("write size false");
        else
        {}
        printf("剩余任务个数%d\n",n);
        if(n == 0)
        break;
    }

    
}


int main()
{
    int pfd[2];
    int rval = pipe(pfd);
    if(rval == -1)
    {
        ERR_EXIT("pipe");
    }
    pid_t fd = fork();
    if(fd == 0)//儿子读
    {
        close(pfd[1]);
        Rwork(pfd[0]);
        close(pfd[0]);
        exit(0);
    }
    else if(fd == -1)
        ERR_EXIT("fork");
    //爹写
    close(pfd[0]);
    Wwork(pfd[1]);
    close(pfd[1]);
    int status = 0;
    waitpid(fd,&status,0);
    printf("childid:%d,parentid:%d,exitcode:%d\n",fd,getpid(),(status>>8)&0xff);


    return 0;
}